package com.example.mysongplayer;
//实现音乐播放MediaPlayer

import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

public class MusicService extends Service {
    private MediaPlayer player;
    private Timer timer;
    public MusicService() {}

    @Override
    public IBinder onBind(Intent intent) {
        return new MusicControl();
    }

    @Override
    public void onCreate(){
        super.onCreate();
        //创建音乐播放器对象
        player = new MediaPlayer();
    }

    //添加用于进度条的计时器
    public void addTimer(){
        if(timer == null){
            timer = new Timer();
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    if(player == null) return;
                    //获取歌曲总时长
                    int duration = player.getDuration();
                    //获取播放进度
                    int currentPosition = player.getCurrentPosition();
                    //创建消息对象
                    Message msg = MusicActivity.handler.obtainMessage();
                    //封装总时长和播放进度至消息对象
                    Bundle bundle = new Bundle();
                    bundle.putInt("duration", duration);
                    bundle.putInt("currentPosition", currentPosition);
                    msg.setData(bundle);
                    //发送消息至主线程的消息队列
                    MusicActivity.handler.sendMessage(msg);

                }
            };
            //开始计时后5ms第一次执行task，此后每500ms执行一次
            timer.schedule(task, 5, 500);

        }
    }

    class MusicControl extends Binder{
        //使用Binder跨进程通信
        public void play(String path){
            //File file = new File(path);
            try{
                //重置音乐播放器
                player.reset();
                //加载多媒体文件
                player = new MediaPlayer();
                //设置播放源
                player.setDataSource(path);
                player.prepare();
                //播放音乐
                player.start();
                //添加计时器
                addTimer();
            }catch (Exception e){
                //捕捉异常不然会报错
                e.printStackTrace();
            }
        }
        //暂停播放
        public void pausePlay(){
                player.pause();
        }
        //继续播放
        public void continuePlay(){
            player.start();
        }
        //设置音乐的播放位置
        public void seekTo(int progress){
            player.seekTo(progress);
        }
    }
    //释放播放器资源
    @Override
    public void onDestroy(){
        super.onDestroy();
        if(player == null) return;
        //停止播放
        if(player.isPlaying())
            player.stop();
        player.release();
        //将player置为空
        player = null;
    }


}